﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server.ActivityFeed;
using System.Collections.Generic;
using System.Security.Principal;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Portal.WebControls;
using eGov.SharePoint.MyPeeps.EventReceivers;
using Microsoft.SharePoint.Administration;

namespace EGOV.Layouts.EGOV
{
    public partial class ListActionFeedsSettings : LayoutsPageBase
    {

        #region ULS Prep

        private static SPDiagnosticsArea logArea;
        private static SPDiagnosticsService logService = SPDiagnosticsService.Local;
        protected static SPDiagnosticsArea LogArea
        {
            get
            {
                if (logArea == null)
                    logArea = new SPDiagnosticsArea("eGov.SharePoint.MyPeeps", new List<SPDiagnosticsCategory>
                    { 
                        new SPDiagnosticsCategory("ListActionFeedsSettings", TraceSeverity.High, EventSeverity.Error),
                        new SPDiagnosticsCategory("ListActionFeedsSettings", TraceSeverity.Verbose, EventSeverity.Information) 
                    });
                return logArea;
            }
        }
        protected static SPDiagnosticsCategory logCategory_Error
        {
            // Indexing if used starts from 1
            get { return LogArea.Categories[1]; }
        }
        protected static SPDiagnosticsCategory logCategory_Information
        {
            // Indexing if used starts from 1
            get { return LogArea.Categories[2]; }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!this.IsPostBack)
            {
                Guid FeedActionsERGiud = Guid.Empty;
                SPList list = SPContext.Current.List;

                bool flagEnabled = ContentActionFeedEventReceiver.IsEventReceiverAttached(list);

                RadioButton rdbYes = (RadioButton)this.FindNestedControl("RadEnableFeedsYes", this.Page);
                RadioButton rdbNo = (RadioButton)this.FindNestedControl("RadEnableFeedsNo", this.Page);
                if (flagEnabled) rdbYes.Checked = true;
                else rdbNo.Checked = true;

                this.ViewState["__REFERER__"] = ResourceFilePath.LayoutsPageUrlWithSubWeb("listedit.aspx") + "?List=" + SPContext.Current.List.ID.ToString("B");
            }
        }

        protected void BtnSave_Click(object sender, EventArgs args)
        {
            SPList list = SPContext.Current.List;
            RadioButton button = (RadioButton)this.FindNestedControl("RadEnableFeedsYes", this.Page);
            bool flag = true;
            if (button.Checked)
            {
                string strProposedRedirect = (string)this.ViewState["__REFERER__"];
                using (SPLongOperation operation = new SPLongOperation(this))
                {
                    operation.Begin();
                    try
                    {
                        flag = ContentActionFeedEventReceiver.ActivateServiceOnList(list);
                    }
                    catch (UserProfileApplicationNotAvailableException exception)
                    {
                        SPUtility.TransferToErrorPage(exception.Message);
                    }
                    finally
                    {
                        operation.End(strProposedRedirect, SPRedirectFlags.DoNotEncodeUrl, HttpContext.Current, null);
                    }
                }
            }
            else ContentActionFeedEventReceiver.DeactivateServiceOnList(list);

            list.Update();

            if (flag) this.Redirect();
        }

        protected void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Redirect();
        }

        private void Redirect()
        {
            string defaultViewUrl = (string)this.ViewState["__REFERER__"];
            if (string.IsNullOrEmpty(defaultViewUrl))
            {
                defaultViewUrl = SPContext.Current.List.DefaultViewUrl;
            }
            SPUtility.Redirect(defaultViewUrl, SPRedirectFlags.DoNotEncodeUrl, HttpContext.Current);
        }

        protected Control FindNestedControl(string id, Control parentControl)
        {
            if (parentControl.ID == id)
            {
                return parentControl;
            }
            foreach (Control control in parentControl.Controls)
            {
                Control control2 = this.FindNestedControl(id, control);
                if (control2 != null)
                {
                    return control2;
                }
            }
            return null;
        }

        //protected bool ActivateServiceOnList(SPList list)
        //{
        //    try
        //    {
        //        //Add the new Event Receiver to the collection
        //        list.EventReceivers.Add(SPEventReceiverType.ItemAdded, EventReceiverAssemblyName, EventReceiverClassName);
        //        list.EventReceivers.Add(SPEventReceiverType.ItemDeleted, EventReceiverAssemblyName, EventReceiverClassName);
        //        list.EventReceivers.Add(SPEventReceiverType.ItemUpdated, EventReceiverAssemblyName, EventReceiverClassName);

        //        logService.WriteTrace(100, logCategory_Information, TraceSeverity.Verbose, String.Format("Custom feeds for List: successfully activated.", new object[] { list.Title }), null);
        //        return true;
        //    }
        //    catch (System.Exception ex)
        //    {
        //        logService.WriteTrace(100, logCategory_Error, TraceSeverity.High,
        //            String.Format("Failed to activate custom feeds for List: {0}. Exception message: {1} \r\n Stack Trace: \r\n {2}", new object[] { list.Title, ex.Message, ex.StackTrace }), null);
        //    }
        //    return false;
        //}

        //protected void DeactivateServiceOnList(SPList list)
        //{
        //    try
        //    {
        //        //Find all receivers in the collection and remove it
        //        List<SPEventReceiverDefinition> toDelete = new List<SPEventReceiverDefinition>();
        //        foreach (SPEventReceiverDefinition eventReceiver in list.EventReceivers)
        //            if (eventReceiver.Class == EventReceiverClassName) toDelete.Add(eventReceiver);

        //        foreach (SPEventReceiverDefinition eventReceiver in toDelete)
        //            eventReceiver.Delete();

        //        logService.WriteTrace(100, logCategory_Information, TraceSeverity.Verbose, String.Format("Custom feeds for List: successfully deactivated.", new object[] { list.Title }), null);
        //    }
        //    catch (System.Exception ex)
        //   {
        //       logService.WriteTrace(100, logCategory_Error, TraceSeverity.High,
        //           String.Format("Failed to deactivate custom feeds for List: {0}. Exception message: {1} \r\n Stack Trace: \r\n {2}", new object[] { list.Title, ex.Message, ex.StackTrace }), null);
        //    }
        //}

        //protected bool IsEventReceiverAttached()
        //{
        //    SPList list = SPContext.Current.List;
        //    if (list != null && list.EventReceivers != null)
        //    {
        //        foreach (SPEventReceiverDefinition eventReceiver in list.EventReceivers)
        //            if (eventReceiver.Class == EventReceiverClassName)
        //                return true;
        //    }
        //    return false;
        //}

    }
}
